package com.sample.springbatch.job.sample.reader;

import com.sample.springbatch.model.RepayOrderInfo;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.RowMapper;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * Created by zwg on 2018/1/12.
 */

public class PartitionerStepSlaveReader<T> extends JdbcPagingItemReader<RepayOrderInfo> {


    @Autowired
    DataSource dataSource;
    @Value("#{stepExecutionContext[userId]}")
    private String userId;

    public PartitionerStepSlaveReader() {

        //setSaveState(false);
        setPageSize(1000);

        setQueryProvider(new MySqlPagingQueryProvider(){{
            setSelectClause("select user_id, product_id");
            setFromClause("from repay_order_info");
            setWhereClause("where user_id = :userId");
            setSortKeys(new HashMap<String, Order>(){{
                put("user_id",Order.ASCENDING);
            }});

        }});

        setRowMapper(new RowMapper<RepayOrderInfo>() {
            @Override
            public RepayOrderInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                RepayOrderInfo  item = new RepayOrderInfo();
                item.setUserId(resultSet.getString("user_id"));
                item.setProductId(resultSet.getString("product_id"));
                return item;
            }
        });




    }


    @PostConstruct
    public void init(){
        setDataSource(dataSource);
    }


    @Override
    protected void doOpen() throws Exception {
        System.out.println("=====userId:"+userId);
        setParameterValues(new HashMap<String,Object>(){{
            put("userId",userId);
        }});
        super.doOpen();
    }
}
